from django.shortcuts import render
from rest_framework.views import APIView
from django.http.response import HttpResponse
from rest_framework.response import Response
from .serializers import MerchantSer, MerchantAddressSer, MerchantGradeSer, CateSer, GoodsSer, Coupon
from .models import Merchant, MerchantAddress, MerchantGrade, Category, Goods, Coupon
import redis
import random
from captcha import image
import jwt
from pro1212 import settings
# Create your views here.


class GenPhoto(APIView):

    def get(self, request):
        uuid = request.query_params.get('uuid')
        number = str(random.randint(10000, 99999))

        rds = redis.Redis(password=123456)

        rds.set(str(uuid), number)

        img = image.ImageCaptcha()
        img_gen = img.generate(number)

        return HttpResponse(img_gen, content_type='image/png')

    def post(self, request):
        account_number = request.data.get('account_number')
        pwd = request.data.get('pwd')
        who = request.data.get('who')
        title = request.data.get('title')
        contact_way = request.data.get('contact_way')
        img = request.data.get('img')
        uuid = request.data.get('uuid')

        rds = redis.Redis(password=123456)

        img_get = rds.get(str(uuid))
        if img_get.decode() != img:
            return Response({
                'code': 401,
                'msg': '图片验证码错误'
            })
        if account_number and pwd and who and title and contact_way:
            d = {
                'account_number': account_number,
                'pwd': pwd,
                'who': who,
                'title': title,
                'contact_way': contact_way,
            }
            Merchant.objects.create(d)
            return Response({
                'code': 200,
                'msg': '商家注册成功'
            })
        else:
            return Response({
                "code": 401,
                'msg': '注册信息不完整'
            })


class LoginView(APIView):

    def post(self, request):
        account_number = request.data.get('account_number')
        pwd = request.data.get('pwd')
        if not account_number or not pwd:
            return Response({
                'code': 401,
                'msg': '登录失败，信息缺失'
            })
        merchant = Merchant.objects.filter(account_number=account_number, pwd=pwd).first()

        if not merchant:
            return Response({
                'code': 401,
                'msg': '用户为注册'
            })
        if merchant.account_number == account_number and merchant.pwd == pwd:
            token = jwt.encode({'id': merchant.id}, key=settings.SECRET_KEY, algorithm='HS256')
            return Response({
                'code': 200,
                'msg': '用户登录成功',
                'token': token
            })
        else:
            return Response({
                'code': 401,
                'msg': '用户账号密码错误'
            })


class AddressView(APIView):

    def post(self, request):
        token = request.data.get('token')
        content = request.data.get('content')
        if not token:
            return Response({
                'code': 401,
                'msg': '用户没有登陆'
            })
        payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms='HS256')

        merchant = Merchant.objects.get(payload['id'])
        MerchantAddress.objects.create(content=content, merchant_is=merchant)
        return Response({
            'code': 200,
            'msg': '地址添加成功'
        })

    def get(self, request):
        token = request.query_params.get('token')

        if not token:
            return Response({
                'code': 401,
                'msg': '用户没有登陆'
            })
        payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms='HS256')

        address = MerchantAddress.objects.filter(merchant_is=payload['id']).all()
        lists = []
        for i in address:
            d = {
                'id': i.id,
                'content': i.content
            }
            lists.append(d)
        return Response({
            'code': 200,
            'msg': '用户信息获取成功',
            'data': lists
        })

    def put(self, request):
        token = request.data.get('token')
        id = request.data.get('id')
        content = request.data.get('content')
        if not content:
            return Response({
                'code': 200,
                'msg': '请输入要修改的地址'
            })
        if not token:
            return Response({
                'code': 401,
                'msg': '用户没有登陆'
            })
        payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms='HS256')
        address = MerchantAddress.objects.filter(id=id, merchant_is=payload['id']).first()
        merchant = Merchant.objects.filter(id=payload['id']).first()
        if not address:
            MerchantAddress.objects.create(content=content, merchant_is=merchant, id=id)
        else:
            address.content = content
            address.save()
        return Response({
            'code': 200,
            'msg': '地址更新成功'
        })



class 